import json
import pandas as pd
import numpy as np

from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from datetime import datetime, timedelta, date

from app.bill.models.tag_department import TagDepartment
from app.service_quality.models.qos_host_disk import QosHostDisk
from app.celery_task.models.celery_task import CeleryTask
from common.aliyun.aliyun_disk import AliYunDisk

from setting import config


class QosHostDiskHandler():
    """  HostDisk Handler
    """
    def __init__(self):
        self.aliyun_disk = AliYunDisk()



    def get_host_disk_search(self, db: Session, quality_date: str, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取磁盘信息
        """
        try:
            result = QosHostDisk.get_host_disk_search(db, quality_date, page, per_page, field, value)
            if not result:
                logger.error(f"get host disk search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get host disk search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result




    def get_host_disk_match(self, db: Session, quality_date: str, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取磁盘信息
        """
        try:
            field_info = {"quality_date": quality_date, field: value}
            result = QosHostDisk.filter_by_field_match(db, page, per_page, field_info)
            if not result:
                logger.error(f"get host disk match, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get host info disk by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result




    def task_update_host_disk_handle(self, db: Session):
        """
        更新磁盘信息的处理函数
        """
        try:
            # 获取所有的磁盘信息
            aliyun_disks_info = self.aliyun_disk.get_all_disks_info()
            if not aliyun_disks_info:
                logger.error(f"get aliyun host_disk failed")
                return False
            
            # 先删除这个日期的数据，防止重合
            quality_date = date.today().strftime("%Y-%m-%d")
            QosHostDisk.delete_by_quality_date(db, quality_date)
            
            for host_disk in aliyun_disks_info:
                # 增加日期信息
                host_disk["quality_date"] = quality_date
                
                result = QosHostDisk.add(db, host_disk)
                if not result:
                    logger.error(f"hostdisk:{host_disk['name']} to database failed")
                    return False
                
        except Exception as e:
            logger.error(f"update host disk error=>{e}")
            return False

        logger.info(f"update host disk success")
        return True




    def task_update_host_disk_start(self, db: Session):
        """
        启动更新磁盘信息的异步任务
        """
        # 启动异步任务
        from app.service_quality.task import qos_update_host_disk_async
        # 判断任务是否已经启动，控制只有一个任务在跑。 如果任务可以多个同时进行，则无需这一步判断。
        task_name = qos_update_host_disk_async.name.split(".")[-1]
        if CeleryTask.is_progress_on_name(db, task_name):
            logger.error(f"task: {task_name} was stared")
            return False

        task = qos_update_host_disk_async.delay()
        task_data = {
            "name": task_name,
            "tid": task.id,
            "state": task.state
        }

        logger.info(f"add task: {task_name} success")
        return task_data



    def post_host_disk_task(self, db: Session):
        """
        启动同步磁盘信息数据到数据库的异步任务
        """
        try:
            result = self.task_update_host_disk_start(db)
            if not result:
                logger.error(f"start task:post_host_disk_task failed")
                return False

        except Exception as e:
            message = f"start task:post_host_disk_task error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result

